'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { login, backupLogin } from '@/lib/user';
import Cookies from 'js-cookie';
import { Form, Input, Button, message, Spin, Card } from 'antd';
import { LockOutlined, UserOutlined, BookOutlined } from '@ant-design/icons';
import { useAuth } from '@/hooks/useAuth';
import Image from 'next/image';

// 环境信息调试函数
const logEnvironmentInfo = () => {
  console.log('%c===== 环境信息 =====', 'color: blue; font-weight: bold');
  console.log('NODE_ENV:', process.env.NODE_ENV);
  console.log('NEXT_PUBLIC_API_URL:', process.env.NEXT_PUBLIC_API_URL);
  console.log('当前URL:', typeof window !== 'undefined' ? window.location.href : 'SSR');
  console.log('当前时间:', new Date().toISOString());
  
  // 检查cookies和localStorage
  const cookies = Object.keys(Cookies.get()).map(key => `${key}: ${Cookies.get(key)?.substring(0, 10)}...`);
  console.log('Cookies:', cookies);
  
  if (typeof window !== 'undefined') {
    const localStorageItems = Object.keys(localStorage).map(key => `${key}: ${localStorage.getItem(key)?.substring(0, 10)}...`);
    console.log('localStorage:', localStorageItems);
  }
  console.log('%c=====================', 'color: blue; font-weight: bold');
};

const LoginPage = () => {
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  const { isAuthenticated, isLoading, checkAuth } = useAuth();

  useEffect(() => {
    // 打印环境信息
    logEnvironmentInfo();
    
    if (!isLoading && isAuthenticated) {
      router.push('/dashboard');
    }
  }, [isLoading, isAuthenticated, router]);

  const onFinish = async (values: { employeeId: string; password: string }) => {
    // 登录前清除所有可能存在的token
    localStorage.removeItem('token');
    sessionStorage.removeItem('token');
    Cookies.remove('token', { path: '/' });
    
    setLoading(true);
    try {
      console.log('准备登录，用户ID:', values.employeeId, '密码(部分):', values.password.substring(0, 1) + '******');
      
      // 显示当前环境信息
      console.log('当前环境变量:', {
        NODE_ENV: process.env.NODE_ENV,
        API_URL: process.env.NEXT_PUBLIC_API_URL,
      });
      
      // 打印所有请求信息
      console.log('【登录请求完整信息】', {
        url: `${process.env.NEXT_PUBLIC_API_URL}/login`,
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': 'application/json'
        },
        body: `employeeId=${values.employeeId}&password=${values.password}`
      });
      
      // 增加额外的错误处理
      let response;
      let useBackupMethod = false;
      
      try {
        // 尝试主要登录方法
        console.log('【尝试主要登录方法】使用axios');
        response = await login(values.employeeId, values.password);
      } catch (directError) {
        console.error('【登录直接异常】', directError);
        
        // 如果主要方法失败，标记使用备用方法
        useBackupMethod = true;
        
        // 如果是跨域错误，它通常没有status，而是network error
        if (directError.message && (
            directError.message.includes('Network Error') || 
            directError.message.includes('Cross-Origin')
          )) {
          console.error('【可能的跨域错误】将尝试备用登录方法');
        }
        
        // 尝试备用登录方法
        console.log('【尝试备用登录方法】使用fetch');
        try {
          const backupResponse = await backupLogin(values.employeeId, values.password);
          console.log('【备用登录成功】', backupResponse);
          response = backupResponse;
        } catch (backupError) {
          console.error('【备用登录也失败】', backupError);
          throw directError; // 抛出原始错误
        }
      }
      
      // 打印原始响应
      console.log('%c===== 登录响应原始数据开始 =====', 'color: green; font-weight: bold');
      console.log('【状态码】:', response.status, response.statusText);
      console.log('【响应头】:', response.headers);
      
      // 测试是否有CORS相关头
      const corsHeaders = {
        'Access-Control-Allow-Origin': response.headers['access-control-allow-origin'],
        'Access-Control-Allow-Credentials': response.headers['access-control-allow-credentials'],
        'Access-Control-Allow-Headers': response.headers['access-control-allow-headers'],
      };
      console.log('【CORS头信息】:', corsHeaders);
      
      console.log('所有响应头:');
      // 打印所有响应头
      const headers = response.headers;
      if (headers && typeof headers.forEach === 'function') {
        headers.forEach((value, key) => {
          console.log(`${key}: ${value}`);
        });
      }
      
      console.log('【响应数据】:', response.data);
      console.log('【响应配置】:', response.config);
      // 转为JSON字符串再打印一次，确保看到所有嵌套属性
      console.log('【响应数据JSON】:', JSON.stringify(response.data, null, 2));
      console.log('%c===== 登录响应原始数据结束 =====', 'color: green; font-weight: bold');
      
      console.log('登录响应主要信息:', {
        status: response.status,
        headers: response.headers,
        data: typeof response.data === 'object' ? { ...response.data } : response.data
      });
      
      // 获取token - 可能在不同位置
      const headerToken = response.headers?.token || response.headers?.['set-token'] || response.headers?.authorization;
      let dataToken = null;
      
      if (response.data) {
        if (typeof response.data === 'string') {
          // 如果数据直接是字符串，可能就是token
          dataToken = response.data;
        } else if (typeof response.data === 'object') {
          // 从对象中获取token
          dataToken = response.data.data || response.data.token || response.data.accessToken;
        }
      }
      
      // 确定使用哪个token
      const token = headerToken || dataToken;
      console.log('提取到的token信息:', { headerToken, dataToken, finalToken: token });
      
      if (token) {
        // 保存token
        Cookies.set('token', token, { expires: 7, path: '/' });
        localStorage.setItem('token', token);
        console.log('Token已保存 ✓');
        
        message.success('登录成功');
        await checkAuth();
        router.push('/dashboard');
        return;
      }
      
      // 检查是否登录成功但没有token
      if (response.status === 200 && response.data) {
        const { code, msg } = typeof response.data === 'object' ? response.data : { code: null, msg: null };
        
        if (code === 1 || msg === 'success') {
          message.warning('登录成功但未获取到token，将尝试继续操作');
          await checkAuth();
          router.push('/dashboard');
          return;
        }
      }
      
      // 如果到这里还没返回，说明没有成功处理
      message.error('登录失败: 无法获取有效的令牌');
    } catch (error: any) {
      console.error('登录错误:', error);
      
      // 先记录所有可能的错误信息
      console.log('%c===== 错误详情开始 =====', 'color: red; font-weight: bold');
      // 输出完整的error对象
      console.log('错误完整对象:', error);
      
      // 是否有响应对象
      if (error.response) {
        console.log('状态码:', error.response.status);
        console.log('状态文本:', error.response.statusText);
        console.log('响应头:', error.response.headers);
        console.log('响应数据:', error.response.data);
        
        // 打印所有响应头
        if (error.response.headers && typeof error.response.headers.forEach === 'function') {
          console.log('所有响应头:');
          error.response.headers.forEach((value: any, key: string) => {
            console.log(`${key}: ${value}`);
          });
        }
        
        // 如果响应数据是对象，尝试JSON序列化以查看所有字段
        if (error.response.data) {
          try {
            console.log('响应数据JSON:', JSON.stringify(error.response.data, null, 2));
          } catch (e) {
            console.log('响应数据无法序列化为JSON');
          }
        }
      }
      
      // 如果有请求信息
      if (error.request) {
        console.log('请求对象:', error.request);
      }
      
      // 输出配置信息
      if (error.config) {
        console.log('请求配置:', {
          url: error.config.url,
          method: error.config.method,
          headers: error.config.headers,
          data: error.config.data
        });
      }
      
      console.log('错误消息:', error.message);
      console.log('%c===== 错误详情结束 =====', 'color: red; font-weight: bold');
      
      // 尝试从错误中提取更多信息
      const statusCode = error.response?.status;
      const responseData = error.response?.data;
      
      let errorMsg = '未知错误';
      
      if (statusCode === 401) {
        console.log('【401错误详情】尝试直接提取信息');
        
        // 获取请求和响应的详细信息
        const requestDetails = error.config ? {
          url: error.config.url,
          method: error.config.method,
          data: error.config.data,
          headers: {
            ...error.config.headers,
            // 移除敏感信息
            'Authorization': error.config.headers?.Authorization ? '[已隐藏]' : undefined,
            'Token': error.config.headers?.Token ? '[已隐藏]' : undefined,
          }
        } : '无请求信息';
        
        console.log('【401请求详情】', requestDetails);
        
        errorMsg = '用户名或密码错误';
        
        // 尝试一个备选登录方法（直接通过fetch）
        try {
          console.log('【尝试登录备选方法】使用fetch');
          
          // 创建表单数据
          const directFormData = new URLSearchParams();
          directFormData.append('employeeId', values.employeeId);
          directFormData.append('password', values.password);
          
          // 添加随机查询参数避免缓存
          const timestamp = new Date().getTime();
          
          // 确保使用正确的API路径
          const directUrl = `/api/login?_t=${timestamp}`;
          console.log('【最终备选登录URL】:', directUrl);
          
          // 创建一个最简单的fetch请求，避免所有复杂配置
          const directFetchResponse = await fetch(directUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: directFormData.toString(),
            credentials: 'omit' // 不包含凭证，避免发送cookie中的token
          });
          
          console.log('【备选登录响应】', {
            status: directFetchResponse.status,
            statusText: directFetchResponse.statusText,
            headers: Array.from(directFetchResponse.headers.entries())
          });
          
          if (directFetchResponse.ok) {
            // 尝试解析响应
            let data;
            try {
              data = await directFetchResponse.json();
            } catch {
              data = await directFetchResponse.text();
            }
            
            console.log('【备选登录成功】', data);
            
            // 尝试提取token
            const token = typeof data === 'object' ? data.data || data.token : data;
            
            if (token) {
              // 保存token
              Cookies.set('token', token, { expires: 7, path: '/' });
              localStorage.setItem('token', token);
              
              message.success('登录成功（备选方法）');
              await checkAuth();
              router.push('/dashboard');
              setLoading(false);
              return;
            }
          }
        } catch (fetchError) {
          console.error('【备选登录失败】', fetchError);
        }
      } else if (responseData) {
        if (typeof responseData === 'string') {
          errorMsg = responseData;
        } else if (typeof responseData === 'object') {
          errorMsg = responseData.msg || responseData.message || responseData.error || '服务器错误';
        }
      } else {
        errorMsg = error.message || '网络错误';
      }
      
      console.error('详细错误:', {
        statusCode,
        responseData,
        errorMsg,
        originalError: error
      });
      
      message.error(`登录失败: ${errorMsg}`);
    } finally {
      setLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (isAuthenticated) {
    router.push('/dashboard');
    return null;
  }

  return (
    <div className="login-container">
      <div className="login-content">
        <Card title="登录" className="login-card">
          <div className="login-box">
            <div className="illustration-wrapper">
              <Image src="/school-illustration.svg" alt="School illustration" width={500} height={500} />
            </div>
            <div className="login-form-wrapper">
              <div className="logo-wrapper">
                <BookOutlined className="logo-icon" />
                <h1>校园人力资源管理系统</h1>
              </div>
              <Form
                name="login"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                className="login-form"
              >
                <Form.Item
                  name="employeeId"
                  rules={[{ required: true, message: '请输入员工ID' }]}
                >
                  <Input prefix={<UserOutlined />} placeholder="员工ID" />
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[{ required: true, message: '请输入密码' }]}
                >
                  <Input.Password prefix={<LockOutlined />} placeholder="密码" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} block>
                    登录
                  </Button>
                </Form.Item>
              </Form>
              <div style={{ textAlign: 'center', marginTop: '16px' }}>
                <Button type="link" href="/public/recruitment">
                  查看招聘公告
                </Button>
              </div>
              <p className="login-form-footer">
                © 2023 校园人力资源管理系统 版权所有
              </p>
            </div>
          </div>
        </Card>
      </div>
      <style jsx global>{`
        .login-container {
          display: flex;
          justify-content: center;
          align-items: center;
          min-height: 100vh;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .login-content {
          max-width: 1200px;
          width: 100%;
          padding: 20px;
        }
        .login-card {
          background-color: white;
          border-radius: 15px;
          box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
          overflow: hidden;
        }
        .login-box {
          display: flex;
          width: 1000px;
          height: 600px;
          overflow: hidden;
        }
        .illustration-wrapper {
          flex: 1;
          background-color: #f5f7ff;
          display: flex;
          align-items: center;
          justify-content: center;
        }
        .login-form-wrapper {
          flex: 1;
          padding: 50px;
          display: flex;
          flex-direction: column;
          justify-content: center;
        }
        .logo-wrapper {
          text-align: center;
          margin-bottom: 40px;
        }
        .logo-icon {
          font-size: 48px;
          color: #1890ff;
        }
        h1 {
          font-size: 24px;
          color: #333;
          margin-top: 10px;
        }
        .login-form {
          max-width: 300px;
          margin: 0 auto;
        }
        .login-form-footer {
          text-align: center;
          margin-top: 20px;
          color: #888;
          font-size: 12px;
        }
        @media (max-width: 768px) {
          .login-box {
            flex-direction: column;
            width: 100%;
            height: auto;
          }
          .illustration-wrapper {
            display: none;
          }
        }
      `}</style>
    </div>
  );
};

export default LoginPage;